package com.jinlejia.erp.ui.customer;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityWriteCustomerFollowBinding;
import com.jinlejia.erp.ui.common.SheetSelect;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 客源跟进
 */
public class WriteCustomerFollowActivity extends AppCompatActivity {


    ArrayList<Map<String, Object>> typeList = new ArrayList<>();
    JSONObject jsonObject = new JSONObject();
    private String url, FOLLOW_WAY_URL;
    ArrayList<Map<String, Object>> reasonList = new ArrayList<>();

    private ActivityWriteCustomerFollowBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_write_customer_follow);
        binding.btBack.setOnClickListener(this::onClick);
        binding.rlFollowType.setOnClickListener(this::onClick);
        binding.btSubmit.setOnClickListener(this::onClick);
        binding.rlFollowReason.setOnClickListener(this::onClick);

        jsonObject.put("resourceCode", getIntent().getStringExtra("code"));
        binding.cCode.setText(getIntent().getStringExtra("code"));
        if (getIntent().getStringExtra("type").equals("sale")) {
            jsonObject.put("type", "1");
            url = ApiConfig.CUSTOMER_FOLLOW;
            FOLLOW_WAY_URL = ApiConfig.CUSTOMER_FOLLOW_WAY;
        } else {
            jsonObject.put("type", "0");
            url = ApiConfig.CUSTOMER_RENT_FOLLOW;
            FOLLOW_WAY_URL = ApiConfig.CUSTOMER_RENT_FOLLOW_WAY;
        }
        getType();
        binding.inputContent.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = 200 - s.length();
                binding.textCount.setText(number + "/200");
                selectionStart = binding.inputContent.getSelectionStart();
                selectionEnd = binding.inputContent.getSelectionEnd();
                if (temp.length() > 200) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    binding.inputContent.setText(s);
                    binding.inputContent.setSelection(tempSelection);//设置光标在最后
                }
            }
        });

        binding.rgMain.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.yes_radio) {
                jsonObject.put("isPublic", "1");
            } else if (checkedId == R.id.no_radio) {
                jsonObject.put("isPublic", "2");
            } else {
                jsonObject.remove("isPublic");
            }
        });

    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.rl_follow_type:
                final SheetSelect typeSelect = new SheetSelect(WriteCustomerFollowActivity.this, "跟进方式", typeList);
                typeSelect.show();
                typeSelect.setOnSelectListener(o -> {
                    Map<String, Object> map = (Map<String, Object>) o;
                    typeSelect.dismiss();
                    binding.followType.setText(map.get("valueName").toString());
                    jsonObject.put("followType", map.get("valuel").toString());
                });
                break;
            case R.id.bt_submit:
                if (!jsonObject.containsKey("isPublic")) {
                    CustomToast.showToast(WriteCustomerFollowActivity.this, "请选择是否公开此条跟进", 1500);
                } else if (!jsonObject.containsKey("followResult")) {
                    CustomToast.showToast(WriteCustomerFollowActivity.this, "请选择跟进结果", 1500);
                } else if (TextUtils.isEmpty(binding.inputContent.getText())) {
                    CustomToast.showToast(WriteCustomerFollowActivity.this, "请输入跟进内容", 1500);
                } else {
                    jsonObject.put("followContent", binding.inputContent.getText().toString());
                    submit();
                }
                break;
            case R.id.rl_follow_reason:

                final SheetSelect reasonSelect = new SheetSelect(WriteCustomerFollowActivity.this, "跟进结果", reasonList);
                reasonSelect.show();
                reasonSelect.setOnSelectListener(o -> {
                    Map<String, Object> map = (Map<String, Object>) o;
                    reasonSelect.dismiss();
                    binding.followReason.setText(map.get("valueName").toString());
                    jsonObject.put("followResult", map.get("valuel").toString());
                    if (!map.get("valueName").toString().equals("接通") && !map.get("valueName").toString().equals("微信或其他")) {
                        binding.inputContent.setText(map.get("valueName").toString());
                    } else {
                        binding.inputContent.setText("");
                    }

                });
                break;
            default:
                break;
        }
    }

    private void getType() {
        OkHttpUtils.get()
                .url(FOLLOW_WAY_URL.concat("/csCode.").concat(getIntent().getStringExtra("code")))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(WriteCustomerFollowActivity.this, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //数据列表
                            typeList = JSON.parseObject(data.getString("customerbasicfollowtype"), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            reasonList = JSON.parseObject(data.getString("genjinjieguo"), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (data.getIntValue("isPublic") == 0) {
                                //私客隐藏公开跟进选择
                                binding.rgLayout.setVisibility(View.GONE);
                            }
                            //默认不公开
                            jsonObject.put("isPublic", "2");
                            //默认跟进方式
                            binding.followType.setText("了解信息");
                            jsonObject.put("followType", "了解信息");

                            binding.followReason.setText(reasonList.get(0).get("valueName").toString());
                            jsonObject.put("followResult", reasonList.get(0).get("valuel").toString());

                        }
                    }
                });
    }

    private void submit() {
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(WriteCustomerFollowActivity.this, response)) {
                            CustomToast.showToast(WriteCustomerFollowActivity.this, "提交成功", 1500);
                            finish();
                        }
                    }
                });
    }

}
